package com.chenshu.shop.config;

import com.chenshu.shop.common.Constant;
import com.chenshu.shop.model.User;
import com.chenshu.shop.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Created with IntelliJ IDEA
 * Description
 * User：chenshu
 * Date：2024-06-18
 * Time：08:36
 */
@Component
public class CartInterceptor implements HandlerInterceptor {
    @Autowired
    CartService cartService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession(false);
        if (session != null) {
            User user = (User) session.getAttribute(Constant.SESSION_USER_INFO_KEY);
            if (user != null) {
                Integer count = cartService.cartCount(user.getId());
                session.setAttribute("cartCount", count);
            }

        }
        return true;
    }
}
